package filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;

/**
 * @author 王俊彪
 * @version 1.0
 */
@WebFilter(filterName = "charsetFilter",urlPatterns = "/user/*",
        initParams = @WebInitParam(name="charset",value = "utf-8"))
public class CharsetFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
//        System.out.println(this + "被初始化");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//        System.out.println(this + "开始执行");
        //处理中文乱码
        FilterRegistration charsetFilter = request.getServletContext().getFilterRegistration("charsetFilter");
        String charset = charsetFilter.getInitParameter("charset");
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset="+charset);
        chain.doFilter(request,response);//放行的时候传递过去的request和response已设置好编码
//        System.out.println(this + "结束执行");
    }

    @Override
    public void destroy() {
//        System.out.println(this + "被销毁");
    }
}
